package cn.ejiakanghu.logistics.service.impl;

import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.ejiakanghu.logistics.service.LogisticsBaseServiceAbstract;
import cn.ejiakanghu.logistics.vo.StoreDeliveryModeEnum;
import cn.ejiakanghu.logistics.vo.WarehouseTypeEnum;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.delivery_manage.AgedmallActivityLgOperationMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.*;
import org.linlinjava.litemall.db.vo.logistics.LogisticsCommonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author houzb
 * @Description
 * @create 2021-11-04 13:34
 */
@Service
public class LogisticsBaseServiceAbstractImpl extends LogisticsBaseServiceAbstract {
    Logger logger = LoggerFactory.getLogger(LogisticsBaseServiceAbstractImpl.class);

    @Resource
    private AgedmallLgReceiveOrderMapper agedmallLgReceiveOrderMapper;

    @Resource
    private AgedmallLgBaseInfoMapper agedmallLgBaseInfoMapper;

    @Resource
    private AgedmallLgMissionMapper agedmallLgMissionMapper;

    @Resource
    private AgedmallActivityLgOperationMapper agedmallActivityLgOperationMapper;

    @Resource
    private AgedmallLgBusiRecordMapper agedmallLgBusiRecordMapper;

    @Resource
    private AgedmallDeliveryManInfoMapper agedmallDeliveryManInfoMapper;

    @Resource
    private AgedmallLgBusiImgMapper agedmallLgBusiImgMapper;

    @Resource
    private OrderStateService orderStateService;


    @Resource
    private AgedmallStoreMapper agedmallStoreMapper;

    /**
     * 判断是否是送货  送货多一个开始送货状态
     */
    public Integer missionIsSendGoods(Integer type) {
        switch (type) {
            case 2:
            case 3:
            case 4:
            case 5:
            case 7:
                return 0;
            default:
                return 1;
        }
    }


    /**
     * 根据传递的参数将信息插入到物流任务信息表 agedmall_lg_mission
     *
     * @param baseInfoId base_info_id 业务信息id
     * @param type       =>type 任务类型
     * @return
     */
    @Override
    public List<Integer> insertIntoOneMission(Integer baseInfoId, int type) {
        return insertIntoOneMissionExec(baseInfoId, type, false);
    }

    /**
     * 创建任务
     *
     * @param baseInfoId
     * @param type
     * @return
     */
    @Override
    public List<Integer> insertIntoOneMissionExec(Integer baseInfoId, int type, boolean isManual) {
        AgedmallLgBaseInfo lgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue());
        List<Integer> missionIds = new ArrayList<>();
        AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(lgBaseInfo.getStoreId().longValue());
        boolean isStoreMission = lgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType() && store.getDistributionMode() != StoreDeliveryModeEnum.MANUAL.getDeliveryMode();
        if (isManual || isStoreMission) {
            AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
            agedmallLgMission.setBaseInfoId(baseInfoId);
            type = lgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode()) ?
                    LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode() : type;
            agedmallLgMission.setType(type);
            agedmallLgMission.setMissionIsOver(missionIsSendGoods(type)); //固定值 1开始状态
            LocalDateTime now = LocalDateTime.now();
            agedmallLgMission.setCreatedTime(now);
            agedmallLgMissionMapper.insertSelective(agedmallLgMission);
            Integer agedmallLgMissionId = agedmallLgMission.getId();
            missionIds.add(agedmallLgMissionId);
            return missionIds;
        }
        return missionIds;
    }

    /**
     * 物流任务信息表的 信息插入 agedmall_lg_mission  后台管理专用
     *
     * @param type agedmalllgmission 任务类型
     * @return
     */
    @Override
    public List<Integer> insertIntoMissonByOrderCodeBackstage(String orderCode, int type) {
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = getAgedmallLgBaseInfosByOrderCode(orderCode);

        List<Integer> missionIds = new ArrayList<>();
        for (AgedmallLgBaseInfo agedmallLgBaseInfo : agedmallLgBaseInfoList) {
            if (agedmallLgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType()) {
                AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
                if (store.getDistributionMode() != StoreDeliveryModeEnum.MANUAL.getDeliveryMode()) {

                    AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
                    agedmallLgMission.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
                    type = agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode()) ?
                            LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode() : type;
                    agedmallLgMission.setType(type);
                    //任务开始
                    agedmallLgMission.setMissionIsOver(missionIsSendGoods(type));
                    LocalDateTime now = LocalDateTime.now();
                    agedmallLgMission.setCreatedTime(now);
                    agedmallLgMissionMapper.insert(agedmallLgMission);
                    Integer missionId = agedmallLgMission.getId();
                    missionIds.add(missionId);

                }
            }
        }
        return missionIds;
    }


    /**
     * 物流任务信息表的 信息插入 agedmall_lg_mission  后台管理专用
     *
     * @param baseInfoId agedmalllgmission 业务信息id
     * @param type       agedmalllgmission 任务类型
     * @return
     */
    @Override
    public List<Integer> insertIntoOneMissionBackstage(Integer baseInfoId, int type) {
        AgedmallLgBaseInfo lgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(baseInfoId.longValue());
        List<Integer> missionIds = new ArrayList<>();

        AgedmallLgMission agedmallLgMission = new AgedmallLgMission();

        agedmallLgMission.setBaseInfoId(baseInfoId);
        type = lgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode()) ?
                LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode() : type;
        agedmallLgMission.setType(type);
        //固定值 1开始状态
        agedmallLgMission.setMissionIsOver(missionIsSendGoods(type));
        LocalDateTime now = LocalDateTime.now();
        agedmallLgMission.setCreatedTime(now);
        agedmallLgMissionMapper.insert(agedmallLgMission);
        Integer agedmallLgMissionId = agedmallLgMission.getId();
        missionIds.add(agedmallLgMissionId);
        return missionIds;
    }

    /**
     * 通过传递的小程序下单单号查询  agedmall_lg_baseInfo
     *
     * @param orderCode agedmall_lg_baseInfo 小程序下单单号
     * @return
     */
    @Override
    public List<AgedmallLgBaseInfo> getAgedmallLgBaseInfosByOrderCode(String orderCode) {
        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        //agedmall_lg_base_info lg_is_over 业务是否结束  固定值 未结束
        agedmallLgBaseInfoExample.createCriteria().andOrderCodeEqualTo(orderCode).andLgIsOverEqualTo(BaseInfoIsOverEnum.START.getCode());
        return agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
    }

    /**
     * 通过传递的小程序下单单号查询  agedmall_lg_baseInfo
     * 根据基础信息表的 小程序下单单号和业务是否结束状态 查询出数据
     *
     * @param orderCode agedmall_lg_baseInfo 小程序下单单号
     * @param type      物流类型
     * @return
     */
    @Override
    public List<AgedmallLgBaseInfo> getAgedmallLgBaseInfosByOrderCode(String orderCode, Integer type) {
        AgedmallLgBaseInfoExample agedmallLgBaseInfoExample = new AgedmallLgBaseInfoExample();
        //agedmall_lg_base_info lg_is_over 业务是否结束  固定值 未结束
        agedmallLgBaseInfoExample.createCriteria().andOrderCodeEqualTo(orderCode).andLgIsOverEqualTo(BaseInfoIsOverEnum.START.getCode()).andLgTypeEqualTo(type);
        return agedmallLgBaseInfoMapper.selectByExampleWithBLOBs(agedmallLgBaseInfoExample);
    }

    /**
     * 将查询出的数据批量插入 agedmall_lg_mission表
     *
     * @param orderCode agedmall_lg_base_info  order_code 用户小程序下单单号
     * @param type      调用接口时传入 为插入的信息的 任务类型
     * @return
     */
    @Override
    public List<Integer> insertIntoMissonByOrderCode(String orderCode, int type) {
      return insertIntoMissonByOrderCodeExec(orderCode, type, false);
    }

    @Override
    public List<Integer> insertIntoMissonByOrderCodeExec(String orderCode, int type, boolean isManual) {
        List<AgedmallLgBaseInfo> agedmallLgBaseInfoList = getAgedmallLgBaseInfosByOrderCode(orderCode);
        List<Integer> missionIds = new ArrayList<>();
        for (AgedmallLgBaseInfo agedmallLgBaseInfo : agedmallLgBaseInfoList) {
            if (agedmallLgBaseInfo.getWarehouseType() == WarehouseTypeEnum.STORE.getWarehouseType()) {
                AgedmallStore store = agedmallStoreMapper.selectByPrimaryKey(agedmallLgBaseInfo.getStoreId().longValue());
                if (isManual || store.getDistributionMode() != StoreDeliveryModeEnum.MANUAL.getDeliveryMode()) {

                    AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
                    agedmallLgMission.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
                    type = agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode()) ?
                            LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode() : type;
                    agedmallLgMission.setType(type);
                    //任务开始
                    agedmallLgMission.setMissionIsOver(missionIsSendGoods(type));
                    LocalDateTime now = LocalDateTime.now();
                    agedmallLgMission.setCreatedTime(now);
                    agedmallLgMissionMapper.insertSelective(agedmallLgMission);
                    Integer missionId = agedmallLgMission.getId();
                    missionIds.add(missionId);

                }
            }
            else{
                AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
                agedmallLgMission.setBaseInfoId(agedmallLgBaseInfo.getId().intValue());
                type = agedmallLgBaseInfo.getLgType().equals(LgBaseInfoLgType.SELFPICKUP.getCode()) ?
                        LogisticsMissionTypeEnum.PICK_YP_ALLOT.getCode() : type;
                agedmallLgMission.setType(type);
                //任务开始
                agedmallLgMission.setMissionIsOver(missionIsSendGoods(type));
                LocalDateTime now = LocalDateTime.now();
                agedmallLgMission.setCreatedTime(now);
                agedmallLgMissionMapper.insertSelective(agedmallLgMission);
                Integer missionId = agedmallLgMission.getId();
                missionIds.add(missionId);
            }
        }
        return missionIds;
    }

    /**
     * agedmall_lg_receive_order 接单信息表的信息插入
     *
     * @param agedmallLgReceiveOrder agedmall_lg_receive_order 插入的详细信息
     * @return
     */
    @Override
    public int insertIntoOneReceiveOrder(AgedmallLgReceiveOrder agedmallLgReceiveOrder) {
        agedmallLgReceiveOrder.setCreatedTime(LocalDateTime.now());
        return agedmallLgReceiveOrderMapper.insert(agedmallLgReceiveOrder);
    }


    /**
     * 更新agedmall_lg_base_info 表中的 当前物流状态
     *
     * @param receiveOrderId agedmall_lg_receive_order  表的id
     * @param stat           agedmall_lg_base_info  表的当前物流状态
     * @return
     */
    @Override
    public int updateBaseInfoLgStatByReceiveOrderId(Integer receiveOrderId, Integer stat) {
        return agedmallActivityLgOperationMapper.updateBaseInfoLgStatByReceiveOrderId(receiveOrderId, stat);
    }


    /**
     * 更新物流任务信息表的 missionIsOver 用于任务类型固定的业务
     *
     * @param id            物流任务信息表的 id
     * @param missionIsOver 任务是否结束
     * @return
     */
    @Override
    public int updateLgMissionMissionIsOver(Integer id, Integer missionIsOver) {
        AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
        agedmallLgMission.setId(id);
        agedmallLgMission.setMissionIsOver(missionIsOver);
        return agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);    //updateByPrimaryKey
    }

    /**
     * 根据 agedmall_lg_base_info的id更新agedmall_lg_base_info当前物流状态ig_stat和lg_is_over 业务是否结束
     *
     * @param id     agedmall_lg_base_info的id
     * @param isOver agedmall_lg_base_info的 lg_is_over 业务是否结束
     * @param stat   gedmall_lg_base_info的 lg_stat 当前的物流状态
     * @return
     */
    @Override
    public int updateBeseInfoLgStatByBaseInfoId(Integer id, Integer isOver, Integer stat) {
        //根据baseinfoId查询出未结束的 baseinfo信息集合
        AgedmallLgBaseInfo agedmallLgBaseInfos = agedmallLgBaseInfoMapper.selectByPrimaryKey(id.longValue());
        int updateByPrimaryKey;
        //baseinfo的LgStat,LgIsOver
        agedmallLgBaseInfos.setLgIsOver(isOver);
        agedmallLgBaseInfos.setLgStat(stat);
        updateByPrimaryKey = agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfos);
        return updateByPrimaryKey;
    }

    /**
     * 接单事件
     * 配送或者配货 根据missionId更新 missionIsOver type的状态
     *
     * @param id         lgMission表的 id
     * @param isOverStat lgMission表的 物流状态
     * @return
     */
    @Override
    public int updateLgMissionMissionIsOverStatById(Integer id, int isOverStat) {
        AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
        agedmallLgMission.setId(id);
        //状态开始
        agedmallLgMission.setMissionIsOver(isOverStat);
        agedmallLgMission.setUpdateTime(LocalDateTime.now());
        return agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
    }

    /**
     * 更新mission表 配货插入的数据的状态
     *
     * @param missionId mission表的id
     * @return
     */

    @Override
    public int updateMissionByMissionId(Integer missionId) {
        AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
        agedmallLgMission.setId(missionId);
        //结束状态
        agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        agedmallLgMission.setUpdateTime(LocalDateTime.now());
        return agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
    }

    /**
     * 更新mission表的 type和misisonIsOver字段
     *
     * @param misisonId
     * @param missionIsOverFlag 用来判断 misison表的isOver 应该是什么状态
     * @return
     */
    @Override
    public List<Integer> updateMissionMissionIsOver(Integer misisonId, Integer missionIsOverFlag) {
        AgedmallLgMission agedmallLgMission = new AgedmallLgMission();
        List<Integer> missionIds = new ArrayList<>();
        agedmallLgMission.setId(misisonId);
        agedmallLgMission.setUpdateTime(LocalDateTime.now());
        //退货中
        if (missionIsOverFlag.equals(LogisticsMissionTypeEnum.RETURN.getCode())) {
            agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
            //换货取货中
        } else if (missionIsOverFlag.equals(LogisticsMissionTypeEnum.CHANGE_PICK_UP.getCode())) {
            agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
            //换货配货中
        } else if (missionIsOverFlag.equals(LogisticsMissionTypeEnum.CHANGE_ALLOT.getCode())) {
            agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
            //换货配送中
        } else if (missionIsOverFlag.equals(LogisticsMissionTypeEnum.CHANGE_DELIVERY.getCode())) {
            agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
        }
        agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
        missionIds.add(agedmallLgMission.getId());
        return missionIds;
    }

    /**
     * 根据id更新lgBusiReCord表的状态
     *
     * @param busiReCordId
     * @param pickupIsCompleteOrReturnIsCompleteFlag 取货完成或者是退货完成标识
     */
    @Override
    public void updateBusiReCordById(Integer busiReCordId, Integer pickupIsCompleteOrReturnIsCompleteFlag) {
        AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
        agedmallLgBusiRecord.setId(busiReCordId.longValue());
        //开始
        agedmallLgBusiRecord.setBusiStat(LgMissionIsOverEum.START.getCode());
        //退货中
        agedmallLgBusiRecord.setLgType(LgBaseInfoStatConstant.BACKING_GOODS);
        //agedmallLgBusiRecord.setBusiTime(LocalDateTime.now());
        agedmallLgBusiRecord.setUpdateTime(LocalDateTime.now());
        agedmallLgBusiRecordMapper.updateByPrimaryKeySelective(agedmallLgBusiRecord);
    }

    /**
     * 更新接单表信息的数据
     *
     * @param receiveOrderId
     */
    @Override
    public void updateReceiveOrderById(Integer receiveOrderId) {
        AgedmallLgReceiveOrder agedmallLgReceiveOrder = new AgedmallLgReceiveOrder();
        agedmallLgReceiveOrder.setId(receiveOrderId.longValue());
        agedmallLgReceiveOrder.setUpdateTime(LocalDateTime.now());
        agedmallLgReceiveOrderMapper.updateByPrimaryKeySelective(agedmallLgReceiveOrder);
    }

    /**
     * 根据missionId查询mission信息
     *
     * @param missionId
     * @param pickupIsCompleteOrReturnIsCompleteFlag 取货完成或者是退货完成标识
     */
    @Override
    public void selectMissionByMissionIdAndUpdateMission(Integer missionId, Integer pickupIsCompleteOrReturnIsCompleteFlag) {
        AgedmallLgMission agedmallLgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        agedmallLgMission.setMissionIsOver(LgMissionIsOverEum.START.getCode());
        agedmallLgMission.setType(LogisticsMissionTypeEnum.RETURN.getCode());
        agedmallLgMission.setUpdateTime(LocalDateTime.now());
        agedmallLgMissionMapper.updateByPrimaryKeySelective(agedmallLgMission);
    }

    /**
     * 插入物流业务记录表
     *
     * @param receiveOrderId 订单id
     * @param missionId      任务id
     */
    @Override
    public Long insertIntoLgBusiRecord(Integer receiveOrderId, Integer missionId) {
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        //agedmall_lg_busi_record
        AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
        agedmallLgBusiRecord.setReceiveOrderId(receiveOrderId.longValue());
        agedmallLgBusiRecord.setBusiTime(LocalDateTime.now());
        //结束
        agedmallLgBusiRecord.setBusiStat(LgMissionIsOverEum.END.getCode());
        //退货
        agedmallLgBusiRecord.setLgType(mission.getType());
        agedmallLgBusiRecord.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        agedmallLgBusiRecord.setCreatedBy("auto");
        agedmallLgBusiRecord.setCreatedTime(LocalDateTime.now());
        agedmallLgBusiRecordMapper.insert(agedmallLgBusiRecord);
        return agedmallLgBusiRecord.getId();
    }

    @Override
    public void insertBusiImg(Long busiId, Integer imgType, String imgUrls) {
        AgedmallLgBusiImg agedmallLgBusiImg = new AgedmallLgBusiImg();
        agedmallLgBusiImg.setCreatedTime(LocalDateTime.now());
        agedmallLgBusiImg.setLgBusiId(busiId);
        agedmallLgBusiImg.setImgType(imgType);
        agedmallLgBusiImg.setUrl(imgUrls);
        agedmallLgBusiImgMapper.insert(agedmallLgBusiImg);
    }

    /**
     * receiveorder表 新增
     *
     * @param agedmallLgBaseInfo
     * @param deliveryManId
     * @param receiverType
     * @param execType
     * @return
     */
    @Override
    public AgedmallLgReceiveOrder insertReceiveOrder(AgedmallLgBaseInfo agedmallLgBaseInfo, Integer deliveryManId, Integer receiverType, Integer execType) {
        AgedmallLgReceiveOrder receiveOrder = new AgedmallLgReceiveOrder();
        if (deliveryManId != null) {
            AgedmallDeliveryManInfo manInfo = agedmallDeliveryManInfoMapper.selectByPrimaryKey(deliveryManId);
            receiveOrder.setUserName(manInfo.getUsername());
            receiveOrder.setPhone(manInfo.getPhone());
        }
        receiveOrder.setLgBaseInfoId(agedmallLgBaseInfo.getId());
        receiveOrder.setReceiveTime(LocalDateTime.now());
        receiveOrder.setOrderCode(agedmallLgBaseInfo.getOrderCode());
        receiveOrder.setReceiveType(receiverType == null ? 1 : receiverType);
        receiveOrder.setLgExecType(execType == null ? 1 : execType);
        receiveOrder.setCreatedTime(LocalDateTime.now());
        receiveOrder.setCreatedBy("auto");
        agedmallLgReceiveOrderMapper.insert(receiveOrder);
        return receiveOrder;
    }

    /**
     * busireceive表的新增
     *
     * @param missionId
     * @param receiverOrderId
     * @param missionType
     * @param orderCode
     * @param busiStat
     * @return
     */
    @Override
    public AgedmallLgBusiRecord insertBusiRecord(Long missionId, Long receiverOrderId, Integer missionType, String orderCode, Integer busiStat) {
        AgedmallLgBusiRecord agedmallLgBusiRecord = new AgedmallLgBusiRecord();
        agedmallLgBusiRecord.setReceiveOrderId(receiverOrderId);
        agedmallLgBusiRecord.setMissionId(missionId);
        agedmallLgBusiRecord.setBusiTime(LocalDateTime.now());
        agedmallLgBusiRecord.setBusiStat(busiStat == null ? 1 : busiStat);
        agedmallLgBusiRecord.setLgType(missionType);
        agedmallLgBusiRecord.setOrderCode(orderCode);
        agedmallLgBusiRecord.setCreatedBy("auto");
        agedmallLgBusiRecord.setCreatedTime(LocalDateTime.now());
        agedmallLgBusiRecordMapper.insert(agedmallLgBusiRecord);
        return agedmallLgBusiRecord;
    }

    /**
     * @param lgContent
     * @return
     */
    @Override
    public List<Integer> getorderGoodsIds(String lgContent) {
        LogisticsCommonData commonData = LogisticsGoodsUtil.parseObject(lgContent);
        List<Integer> orderGoodsId = new ArrayList<>();
        commonData.getGoodsDataList().forEach(goods -> orderGoodsId.add(goods.getOrderGoodsId()));
        return orderGoodsId;
    }

    /**
     * 更新orderGoods表的状态
     *
     * @param lgContent
     * @param state
     */
    @Override
    public void updateOrderGoodsStat(String lgContent, Integer state) {
        List<Integer> orderGoodsId = getorderGoodsIds(lgContent);
        orderStateService.modifyOrderGoodsStateBatch(orderGoodsId, state);
    }

    /**
     * 更新图片表
     *
     * @param busiId
     * @param imgType
     * @param imgUrls
     */
    @Override
    public void updateBusiImg(Long busiId, Integer imgType, String imgUrls) {
        AgedmallLgBusiImg agedmallLgBusiImg = new AgedmallLgBusiImg();
        agedmallLgBusiImg.setUpdateTime(LocalDateTime.now());
        agedmallLgBusiImg.setImgType(imgType);
        agedmallLgBusiImg.setUrl(imgUrls);
        agedmallLgBusiImgMapper.updateByPrimaryKeySelective(agedmallLgBusiImg);
    }

    @Override
    public String base64ToUrl(List<String> base64Img) {
        String path = "app/logistics/";
        String realPath = "";
        List<String> ossUrls = new ArrayList<>();
        try {
            if (SystemUtil.isWindows()) {
                realPath = UploadConstant.WINDOS_BASE_UPLOAD_URL + path;
            } else if (SystemUtil.isMacOS() || SystemUtil.isMacOSX()) {
                realPath = UploadConstant.MAC_BASE_UPLOAD_URL + path;
            } else {
                realPath = UploadConstant.LINUX_BASE_UPLOAD_URL + path;
            }
            for (int i = 0; i < base64Img.size(); i++) {
                String ossUrl = "";

                String fileName = "uploadLogistics-" + IdUtil.fastSimpleUUID() + ".jpg";
                FileUtil.mkdir(new File(realPath));
                String savePath = realPath + fileName;
                String ossPath = path + fileName;
                String isSave = Base64Util.generateImage(base64Img.get(i).substring(23), savePath);
                logger.info("图片保存错误：{}", isSave);
                logger.info("图片保存路径：{}", savePath);
                if (StrUtil.isNotBlank(isSave)) {
                    return null;
                }
                OssUtil ossUtil = new OssUtil();
                //TODO 上传到oss
                ossUrl = ossUtil.uploadFile(savePath, ossPath);
                ossUrls.add(ossUrl);
            }
        } catch (Exception e) {
            logger.error("图片转换失败：{}", e);
            return null;
        }

        return String.join(",", ossUrls);
    }

    /**
     * 根据missionId更新baseInfo的LgStat
     *
     * @param missionId
     * @param baseLgStat 当前的物流状态
     */
    @Override
    public void updateBaseInfoLgStatByMissionId(Integer missionId, Integer baseLgStat) {
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        agedmallLgBaseInfo.setLgStat(baseLgStat);
        agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
    }


    /**
     * 根据missionId修改baseInfo的LgStat，LgIsOver
     *
     * @param missionId
     * @param lgStat
     */
    @Override
    public void updateLgBaseInfoLgStatAndLgIsOverByMissionId(Integer missionId, Integer lgStat) {
        AgedmallLgMission agedmallLgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = new AgedmallLgBaseInfo();
        agedmallLgBaseInfo.setId(agedmallLgMission.getBaseInfoId().longValue());
        agedmallLgBaseInfo.setUpdateTime(LocalDateTime.now());
        agedmallLgBaseInfo.setLgStat(lgStat);
        agedmallLgBaseInfo.setLgIsOver(LgBaseInfoIsOverEnum.END.getCode());
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
    }

    /**
     * receiveorder busiorder busiimg 通用的插入操作以及baseinfo的状态更新操作
     *
     * @param manId
     * @param missionId
     * @param messageType
     * @param receiveType
     * @param execType
     */
    @Override
    public void logisticsEventInProgress(Integer manId, Integer missionId, Integer messageType, Integer receiveType, Integer execType) {
        //更新数据
        AgedmallLgMission mission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(mission.getBaseInfoId().longValue());
        Integer stat = LgBaseInfoStatConstant.getNowStat(agedmallLgBaseInfo.getLgType(), messageType);
        agedmallLgBaseInfo.setLgStat(stat);
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);

        //新增agedmall_lg_receive_order  agedmall_lg_busi_record
        AgedmallLgReceiveOrder receiveOrder = insertReceiveOrder(agedmallLgBaseInfo, manId, receiveType, execType);
        insertBusiRecord(mission.getId().longValue(), receiveOrder.getId(), mission.getType(), agedmallLgBaseInfo.getOrderCode(), null);

        //更改订单商品的状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), stat);
    }

    /**
     * 配货完成操作
     *
     * @param missionId
     * @param imgs
     * @param nowLgStat
     * @param completeLgStat
     * @param errorMsg
     */
    @Override
    public boolean pickingCompleteOperation(Integer missionId, List<String> imgs, int nowLgStat, int completeLgStat, String errorMsg) {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(nowLgStat)) {
            throw new BizException(errorMsg);
        }

        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);

        //更新状态
        List<Integer> missionList = new ArrayList<>();
        //修改当前baseInfo状态
        Integer baseInfoState = completeLgStat;
        AgedmallLgBusiRecord agedmallLgBusiRecord = insertBusiRecord(lgMission.getId().longValue(), null, lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //保存拍照上传的图片
        //插入img表
        if (imgs.size() != 0) {
            String url = base64ToUrl(imgs);
            if (StrUtil.isBlank(url)) {
                logger.error("图片转换错误：{}", url);
                throw new BizException("图片转换错误");
            }
            insertBusiImg(agedmallLgBusiRecord.getId(), 1, url);
        }
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        //修改状态 lgIsOver
        if (completeLgStat == LgBaseInfoStatConstant.CHANGE_SEND_COMPLETE || completeLgStat == LgBaseInfoStatConstant.RETURN_COMPLETE
                || completeLgStat == LgBaseInfoStatConstant.MAINTAIN_COMPLETE || completeLgStat == LgBaseInfoStatConstant.BACK_GOODS_COMPLETE) {
            agedmallLgBaseInfo.setLgIsOver(BaseInfoIsOverEnum.END.getCode());
        }
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
        return true;
    }

    /**
     * 配送完成操作
     *
     * @param missionId
     * @param nowLgStat
     * @param completeLgStat
     * @param errorMsg
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean deliveryCompletionOperation(Integer missionId, int nowLgStat, int completeLgStat, String errorMsg) {
        //根据missionId更新物流信息
        AgedmallLgMission lgMission = agedmallLgMissionMapper.selectByPrimaryKey(missionId);
        lgMission.setMissionIsOver(LgMissionIsOverEum.END.getCode());
        AgedmallLgBaseInfo agedmallLgBaseInfo = agedmallLgBaseInfoMapper.selectByPrimaryKey(lgMission.getBaseInfoId().longValue());
        if (!agedmallLgBaseInfo.getLgStat().equals(nowLgStat)) {
            throw new BizException(errorMsg);
        }
        agedmallLgMissionMapper.updateByPrimaryKeySelective(lgMission);
        //修改当前baseInfo状态
        Integer baseInfoState = completeLgStat;
        //更新状态
        List<Integer> missionList = new ArrayList<>();
        insertBusiRecord(lgMission.getId().longValue(), null, lgMission.getType(), agedmallLgBaseInfo.getOrderCode(), 2);
        //修改baseInfo状态
        agedmallLgBaseInfo.setLgStat(baseInfoState);
        //修改状态 lgIsOver
        if (completeLgStat == LgBaseInfoStatConstant.CHANGE_SEND_COMPLETE || completeLgStat == LgBaseInfoStatConstant.RETURN_COMPLETE
                || completeLgStat == LgBaseInfoStatConstant.MAINTAIN_COMPLETE || completeLgStat == LgBaseInfoStatConstant.BACK_GOODS_COMPLETE) {
            agedmallLgBaseInfo.setLgIsOver(BaseInfoIsOverEnum.END.getCode());
        }
        agedmallLgBaseInfoMapper.updateByPrimaryKeySelective(agedmallLgBaseInfo);
        //同步修改orderGoods状态
        updateOrderGoodsStat(agedmallLgBaseInfo.getLgContent(), baseInfoState);
        return true;
    }
}
